<?php


namespace app\api\controller\shouye;

use app\common\controller\Api;
use think\Db;
use \app\admin\model\xc\dynamics\Info as InfoModel;
use \app\admin\model\xc\dynamics\Likes as LikesModel;
use \app\admin\model\xc\dynamics\Posts as PostsModel;
use \app\admin\model\xc\dynamics\Type as TypeModel;
use \app\admin\model\xc\dynamics\Collect as CollectModel;
use Carbon\Carbon;
use app\common\model\User;

class Dynamics extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获取动态版块
     */
    public function type()
    {
        $this->success('获取成功', TypeModel::select());
    }

    /**
     * 获取动态列表
     */
    public function infoList($type_id = 0, $name = null)
    {
        $where = [];
        if ($type_id != 0) {
            $where["type_id"] = $type_id;
        }
        if ($name != null) {
            $list = InfoModel::with("type")
                ->where(InfoModel::getTable() . ".name", "like", "%$name%")
                ->where($where)
                ->order("create_time", "desc")
                ->paginate()
                ->each(function ($info, $key) {
                    // $info->user = User::get(["id" => $info->user_id]);
                    $info->user_num = PostsModel::where('in_id', $info->id)
                        ->group('user_id')
                        ->count();
                    $info->posts_num = PostsModel::where('in_id', $info->id)
                        ->count();
                });
        } else {
            $list = InfoModel::with("type")
                ->where($where)
                ->order("create_time", "desc")
                ->paginate()
                ->each(function ($info, $key) {
                    // $info->user = User::get(["id" => $info->user_id]);
                    $info->user_num = PostsModel::where('in_id', $info->id)
                        ->group('user_id')
                        ->count();
                    $info->posts_num = PostsModel::where('in_id', $info->id)
                        ->count();
                });
        }



        $this->success('获取成功', $list);
    }


    /**
     * 动态详情
     */
    public function details($id)
    {
        $details = InfoModel::with("type")->where(InfoModel::getTable() . ".id", $id)->find();
        // $this->success('获取成功', $details);
        $details->user_num = PostsModel::where('in_id', $details->id)
            ->group('user_id') // 按 user_id 分组
            ->count(); // 统计分组后的数量

        // $details->user = User::where("id", $details->user_id)->field('id,nickname,avatar')->find();
        $details->posts_num = PostsModel::where('in_id', $details->id)
            ->count();
        $details['collect_num'] = CollectModel::where("in_id", $id)->count();
        $details['likes_num'] = LikesModel::where("in_id", $id)->where("inpo", 1)->count();
        $details['collect_status'] = false;
        $details['likes_status'] = false;
        if ($this->auth->id) {
            $Likes = LikesModel::where("in_id", $id)->where("user_id", $this->auth->id)->where("inpo", 1)->find();
            if ($Likes) {
                $details['likes_status'] = true;
            }
            $collect =  CollectModel::where("in_id", $id)->where("user_id", $this->auth->id)->find();
            if ($collect) {
                $details['collect_status'] = true;
            }
        }
        $this->success('获取成功', $details);
    }

    /**
     * 动态浏览
     */
    public function browse($id)
    {
        InfoModel::where("id", $id)->setInc("see_num");
    }
    /**
     * 动态分享
     */
    public function share($id)
    {
        InfoModel::where("id", $id)->setInc("replies");
    }

    /**
     * 动态点赞
     */
    public function infoLikes($id)
    {
        $Likes =  LikesModel::where("in_id", $id)->where("user_id", $this->auth->id)->where("inpo", 1)->find();
        if ($Likes) {
            $delete = LikesModel::where("in_id", $id)->where("user_id", $this->auth->id)->where("inpo", 1)->delete();
            if ($delete) {
                $this->success('删除成功');
            }
        } else {
            $insert = LikesModel::insert(["in_id" => $id, "user_id" => $this->auth->id, "inpo" => 1, "create_time" => time()]);
            if ($insert) {
                $this->success('点赞成功');
            }
        }
        $this->error('操作失败');
    }

    /**
     * 动态评论列表
     */
    public function postsList($id)
    {
        Carbon::setLocale('zh');
        $now = Carbon::now(); // 当前时间
        $list = PostsModel::where("in_id", $id)
            ->where("type", 1)
            ->order("create_time", "desc")
            ->paginate()
            ->each(function ($posts, $key) use ($id, $now) {
                $posts->likes_status = false;
                if ($this->auth->id) {
                    $Likes = LikesModel::where("in_id", $id)->where("user_id", $this->auth->id)->where("po_id", $posts->id)->where("inpo", 2)->find();
                    if ($Likes) {
                        $posts->likes_status = true;
                    }
                }
                $posts->likes_num = LikesModel::where("in_id", $id)->where("po_id", $posts->id)->count();
                // 将时间戳转换为 Carbon 实例
                $createTimeInstance = Carbon::createFromTimestamp($posts->create_time);
                // 获取时间差（友好格式）
                $posts->time_distance = $createTimeInstance->diffForHumans($now);

                $posts->user = User::where("id", $posts->user_id)->field('id,nickname,avatar')->find();
                $posts->posts_num = PostsModel::where("po_id", $posts->id)->where("type", 2)->count();
                $posts->posts_num_show = false;
                $posts->posts_num_state = false;
                if ($posts->posts_num > 1) {
                    $posts->posts_num_state = true;
                }
                $posts->posts = PostsModel::where("po_id", $posts->id)->where("type", 2)->order("create_time", "desc")->limit(1)->select();
                foreach ($posts->posts as $key => $value) {
                    $value->user = User::where("id", $value->user_id)->field('id,nickname,avatar')->find();
                    $value->likes_status = false;
                    if ($this->auth->id) {
                        $Likes = LikesModel::where("in_id", $id)->where("user_id", $this->auth->id)->where("po_id", $value->id)->where("inpo", 2)->find();
                        if ($Likes) {
                            $value->likes_status = true;
                        }
                    }
                    $value->likes_num = LikesModel::where("in_id", $id)->where("po_id", $value->id)->count();
                    // 将时间戳转换为 Carbon 实例
                    $createTimeInstance = Carbon::createFromTimestamp($value->create_time);
                    // 获取时间差（友好格式）
                    $value->time_distance = $createTimeInstance->diffForHumans($now);
                }
            });
        $this->success('获取成功', $list);
    }
    /**
     * 动态回复列表
     */
    public function postsHfList($id, $po_id)
    {
        Carbon::setLocale('zh');
        $now = Carbon::now(); // 当前时间
        $list = PostsModel::where("in_id", $id)->where("po_id", $po_id)->where("type", 2)->order("create_time", "desc")->select();
        foreach ($list as $key => $value) {
            $value->user = User::where("id", $value->user_id)->field('id,nickname,avatar')->find();
            $value->likes_status = false;
            if ($this->auth->id) {
                $Likes = LikesModel::where("in_id", $id)->where("user_id", $this->auth->id)->where("po_id", $value->id)->where("inpo", 2)->find();
                if ($Likes) {
                    $value->likes_status = true;
                }
            }
            $value->likes_num = LikesModel::where("in_id", $id)->where("po_id", $value->id)->count();

            // 将时间戳转换为 Carbon 实例
            $createTimeInstance = Carbon::createFromTimestamp($value->create_time);
            // 获取时间差（友好格式）
            $value->time_distance = $createTimeInstance->diffForHumans($now);
        }
        $this->success('获取成功', $list);
    }

    /**
     * 动态回复
     */
    public function postssubmit()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params['user_id'] = $this->auth->id;
            $params['create_time'] = time();
            // $this->success('提交成功', $params);
            $record = PostsModel::insert($params);
            if ($record) {
                // InfoModel::where("id", $params['in_id'])->setInc("replies");
                $this->success('提交成功');
            }
            $this->error('提交失败');
        }
        $this->error('非法请求');
    }

    /**
     * 动态回复删除
     */
    public function postsDel($id)
    {
        $delete =  PostsModel::where("id", $id)->delete();
        if ($delete) {
            LikesModel::where("po_id", $id)->delete();
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 动态回复点赞
     */
    public function postsLikes($id, $po_id, $inpo)
    {
        $Likes =  LikesModel::where("in_id", $id)->where("po_id", $po_id)->where("user_id", $this->auth->id)->where("inpo", $inpo)->find();
        if ($Likes) {
            $delete = LikesModel::where("in_id", $id)->where("po_id", $po_id)->where("user_id", $this->auth->id)->where("inpo", $inpo)->delete();
            if ($delete) {
                $this->success('删除成功');
            }
        } else {
            $insert = LikesModel::insert(["in_id" => $id, "po_id" => $po_id, "user_id" => $this->auth->id, "inpo" => $inpo, "create_time" => time()]);
            if ($insert) {
                $this->success('点赞成功');
            }
        }
        $this->error('操作失败');
    }

    /**
     * 动态收藏
     */
    public function collect($id)
    {
        $collect =  CollectModel::where("in_id", $id)->where("user_id", $this->auth->id)->find();
        if ($collect) {
            $delete = CollectModel::where("in_id", $id)->where("user_id", $this->auth->id)->delete();
            if ($delete) {
                $this->success('已取消');
            }
        } else {
            $insert = CollectModel::insert(["in_id" => $id, "user_id" => $this->auth->id, "create_time" => time()]);
            if ($insert) {
                $this->success('收藏成功');
            }
        }
        $this->error('操作失败');
    }

    /**
     * 获取动态收藏列表
     */
    public function collectList($type_id = 0, $name = null)
    {
        // 获取当前用户收藏的数据
        $collect = CollectModel::where("user_id", $this->auth->id)->select();

        // 提取出用户收藏的 in_id 列表
        $asd = [];
        foreach ($collect as $key => $value) {
            $asd[] = $value->in_id;
        }

        // 设置当前时间并初始化查询条件
        Carbon::setLocale('zh');
        $now = Carbon::now(); // 当前时间
        $where = [];

        // 如果传递了 type_id，则将其加入查询条件
        if ($type_id != 0) {
            $where["type_id"] = $type_id;
        }
        if ($name != null) {
            $list = InfoModel::with("type")
                ->where($where)
                ->where(InfoModel::getTable() . ".name", "like", "%$name%")
                ->whereIn(InfoModel::getTable() . ".id", $asd) // 使用 whereIn 更加语义化
                ->order("create_time", "desc")
                ->paginate()
                ->each(function ($info) use ($now) {
                    // 获取与信息关联的用户
                    $info->user = User::get(["id" => $info->user_id]);

                    // 获取该信息的评论数据
                    $info->user_num = PostsModel::where('in_id', $info->id)
                        ->group('user_id')
                        ->count();
                    $info->posts_num = PostsModel::where('in_id', $info->id)
                        ->count();

                    // 将时间戳转换为 Carbon 实例并计算时间差
                    $createTimeInstance = Carbon::createFromTimestamp($info->create_time);
                    $info->time_distance = $createTimeInstance->diffForHumans($now);
                });
        } else {
            $list = InfoModel::with("type")
                ->where($where)
                ->whereIn(InfoModel::getTable() . ".id", $asd) // 使用 whereIn 更加语义化
                ->order("create_time", "desc")
                ->paginate()
                ->each(function ($info) use ($now) {
                    // 获取与信息关联的用户
                    $info->user = User::get(["id" => $this->auth->id]);

                    // 获取该信息的评论数据
                    $info->user_num = PostsModel::where('in_id', $info->id)
                        ->group('user_id')
                        ->count();
                    $info->posts_num = PostsModel::where('in_id', $info->id)
                        ->count();

                    // 将时间戳转换为 Carbon 实例并计算时间差
                    $createTimeInstance = Carbon::createFromTimestamp($info->create_time);
                    $info->time_distance = $createTimeInstance->diffForHumans($now);
                });
        }
        // 查询 InfoModel 表，并根据收藏的 in_id 进行过滤



        // 返回成功的响应，并包含分页数据
        $this->success('获取成功', $list);
    }






    /**
     * 获取动态关注列表
     */
    public function likesList($type_id = 0)
    {
        // 获取当前用户收藏的数据
        $collect = LikesModel::where("user_id", $this->auth->id)->select();

        // 提取出用户收藏的 in_id 列表
        $asd = [];
        foreach ($collect as $key => $value) {
            $asd[] = $value->in_id;
        }

        // 设置当前时间并初始化查询条件
        Carbon::setLocale('zh');
        $now = Carbon::now(); // 当前时间
        $where = [];

        // 如果传递了 type_id，则将其加入查询条件
        if ($type_id != 0) {
            $where["type_id"] = $type_id;
        }

        // 查询 InfoModel 表，并根据收藏的 in_id 进行过滤
        $list = InfoModel::with("type")
            ->where($where)
            ->whereIn(InfoModel::getTable() . ".id", $asd) // 使用 whereIn 更加语义化
            ->order("create_time", "desc")
            ->paginate()
            ->each(function ($info) use ($now) {
                // 获取与信息关联的用户
                $info->user = User::get(["id" => $this->auth->id]);

                // 获取该信息的评论数据
                $info->user_num = PostsModel::where('in_id', $info->id)
                    ->group('user_id')
                    ->count();
                $info->posts_num = PostsModel::where('in_id', $info->id)
                    ->count();

                // 将时间戳转换为 Carbon 实例并计算时间差
                $createTimeInstance = Carbon::createFromTimestamp($info->create_time);
                $info->time_distance = $createTimeInstance->diffForHumans($now);
            });


        // 返回成功的响应，并包含分页数据
        $this->success('获取成功', $list);
    }
}
